﻿#include "OiPCH.hpp"
#include "OiLeaderTech_UDP.hpp"
#include <QUdpSocket>
#include <QHostAddress>
#include <QNetworkProxy>

namespace Oi
{
    namespace PLScannerCore
    {
        class Leader_UdpImpl : public Impl<Leader_Udp>
        {
        public:
            void init();

        public:
            QUdpSocket* _udp;

        public:
            bool _ready;
            QString _addr;
            int _port;

        public:
            double _value;
        };

        void Leader_UdpImpl::init()
        {
            OI_Q(Leader_Udp);

            _udp = new QUdpSocket(q);

            auto settings = Core::OiSettings();
            _addr = settings->value("Leader_Udp/Address", "10.6.33.98").toString();
            _port = settings->value("Leader_Udp/Port", "7000").toInt();

            _ready = _udp->bind(_port, QUdpSocket::ShareAddress);

            q->connect(_udp, SIGNAL(readyRead()), q, SLOT(onUdpReadReady()));
        }

        Leader_Udp::Leader_Udp(QObject* parent /*= nullptr*/)
            : QObject(parent)
        {
            OI_I(Leader_Udp);
            init();
        }

        Leader_Udp::~Leader_Udp()
        {
            OI_I(Leader_Udp);
            exit();
        }

        void Leader_Udp::init()
        {
            OI_IMPL()->init();
        }

        void Leader_Udp::exit()
        {
            OI_E(Leader_Udp);

            d->_udp->abort();
            delete d->_udp;
        }

        void Leader_Udp::onUdpReadReady()
        {
            OI_F(Leader_Udp);

            while(d->_udp->hasPendingDatagrams())
            {
                QByteArray data;

                data.resize(d->_udp->pendingDatagramSize());

                d->_udp->readDatagram(data.data(), data.size());

                if (data.size() >= 1)
                {
                    int16_t value = 0;

                    QDataStream ds(&data, QIODevice::ReadOnly);
                    ds >> value;

                    d->_value = 0.1 * value;
                }
            }
        }

        double Leader_Udp::value() const
        {
            return OI_IMPL()->_value;
        }
  

        Leader_Udp* Leader_Udp::instance()
        {
            static Leader_Udp s_hankook_Tcp;
            return &s_hankook_Tcp;
        }
    }
}